﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mbs.Utils.ImageHelper
{
    public static class ExtendMethods
    {
        /// <summary>
        /// 功能:转换objValue为int
        /// [11-03-09 10:10  周三 lxw]<para />
        /// </summary>
        /// <param name="objValue">源对象</param>
        /// <param name="iDefault">默认值</param>
        /// <param name="throwE">是否抛出异常</param>
        /// <returns>如果错误,返回0</returns>
        public static int toint32(this object objValue, int iDefault = 0, bool throwE = false)
        {
            try
            {
                int t;
                if (Int32.TryParse(objValue.ToString().Split('.')[0], out t))
                    return t;
                else
                {
                    if (throwE) throw new Exception("转换失败:" + objValue.tostr());
                    return iDefault;
                }

            }
            catch (Exception error)
            {
                if (throwE) throw error;
                return iDefault;
            }
        }

        /// <summary>
        /// 循环foreach
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objValue"></param>
        /// <param name="fun"></param>
        public static void Foreach<T>(this IEnumerable<T> objValue, Action<T> fun)
        {
            foreach (T t in objValue)
            {
                fun(t);
            }
        }

        /// <summary>
        /// 功能:转换objValue为String,主要区别于ToString， ToStr为安装转换，可以用ToStr代替toString,string a = null;string b = a.ToStr();string c = a.ToString();
        /// [11-03-10 09:23  周四 lxw]<para />
        /// [11-03-09 10:10  周三 lxw]<para />
        /// </summary>
        /// <param name="objValue">源对象</param>
        /// <param name="sDefault">默认值</param>
        /// <param name="throwE">是否抛出异常</param>
        /// <returns>如果错误,返回""</returns>
        public static string tostr(this object objValue, string sDefault = "", bool throwE = false)
        {
            try
            {
                return objValue.ToString();
            }
            catch (Exception error)
            {
                if (throwE) throw error;
                return sDefault;
            }
        }
    }
}
